import { Injectable } from '@angular/core';
import { combineLatest, Observable, of, Subject } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { TransactionService, UserWalletService, UserWithdrawalAddressService } from '../../../core/service';
import { StorageService } from '../../../core/sotrage/storage.service';
import { CommonResponse, ReqWithdrawal, ResWalletBalance, UserWithdrawalAddressMobileList } from '../../../model';
import { ApiService } from 'src/app/core/api';

@Injectable()
export class TransferService {

  private goBackUrlSource = new Subject<string>();

  goBackUrl$ = this.goBackUrlSource.asObservable();

  changeGoBackUrl(url: string) {
    this.goBackUrlSource.next(url);
  }

  doTransfer(data: ReqWithdrawal) {
    return this.transactionService.requestUserTransactionForWithdrawal(data);
  }

  getTransfer(transactionId: string) {
    return this.transactionService.userTransaction({
      transactionId: transactionId
    });
  }

  getCoinName() {
    const data = this.storage.get<{ coinName: string }>('coin');
    const coinName = data ? (data.coinName || 'LCash') : 'LCash';
    return coinName;
  }
  listAllTransfer(): Observable<Array<UserWithdrawalAddressMobileList>> {
    const data = this.storage.get<{ coinName: string }>('coin');
    const coinName = data ? (data.coinName || '') : '';
    return this.userWithdrawalAddressService.userWithdrawalAddressMobileList({
      coinName: coinName,
      pageNo: '1',
    }).pipe(
      switchMap(value => {
        const results = [];
        results.push(of(value.data.list));
        const pages = value.data.pages;
        for (let i = 1; i < pages; i++) {
          const result = this.userWithdrawalAddressService.userWithdrawalAddressMobileList({
            coinName: coinName,
            pageNo: pages + '',
          }).pipe(
            map(res => res.data.list)
          );
          results.push(result);
        }
        return combineLatest(results);
      }),
      map(res => res.reduce((a: UserWithdrawalAddressMobileList[], b: UserWithdrawalAddressMobileList[]) => a.concat(b))),
      map(res => res as UserWithdrawalAddressMobileList[])
    );
  }

  getWalletInfo(): Observable<CommonResponse<ResWalletBalance>>  {
    const coinName = this.storage.get<{ coinName: string }>('coin').coinName || '';
    return this.userWalletService.getUserWalletBalanceForWithdrawal({
      coinName: coinName,
    });
  }

  error(e: any) {
    this.api.goToWhere(e);
  }

  constructor(
    private api: ApiService,
    private transactionService: TransactionService,
    private storage: StorageService,
    private userWithdrawalAddressService: UserWithdrawalAddressService,
    private userWalletService: UserWalletService
  ) { }
}
